package com.atguigu.flink.chapter11;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/12/21 10:04
 */
public class Flink02_Table_BaseUse_Agg {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
    
        DataStreamSource<WaterSensor> waterSensorStream =
            env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                             new WaterSensor("sensor_1", 2000L, 20),
                             new WaterSensor("sensor_2", 3000L, 30),
                             new WaterSensor("sensor_1", 4000L, 40),
                             new WaterSensor("sensor_1", 5000L, 50),
                             new WaterSensor("sensor_2", 6000L, 60));
        
        
        // 1. 获取一个表的环境
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        // 2. 把流转成一个动态表 表的列名默认就是属性名
        Table table = tEnv.fromDataStream(waterSensorStream);
        // 3. 在动态表上执行连续查询, 得到一个新的动态表  select id, sum(vc) vc_sum from t group by id
    
        /*Table resultTable = table
            .groupBy($("id"))
            .aggregate($("vc").sum().as("vc_sum"))
            .select($("id"), $("vc_sum"));*/
    
        Table resultTable = table
            .groupBy($("id"))
            .select($("id"), $("vc").max().as("vc_sum"));
    
        //resultTable.execute().print();
        DataStream<Tuple2<Boolean, Row>> resultStream = tEnv.toRetractStream(resultTable, Row.class);
        resultStream.filter(t -> t.f0).map(t -> t.f1).print();
    
        
        env.execute();
    
       
        
    }
}
